package view.admin;

import controller.UserController;
import model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Comparator;
import java.util.List;

/**
 * 用户管理面板
 */
public class UserManagementPanel extends JPanel {
    private UserController userController;

    private JTable userTable;
    private DefaultTableModel tableModel;
    private TableRowSorter<DefaultTableModel> tableSorter;
    private JButton resetPasswordButton;
    private JButton deleteUserButton;
    private JButton refreshButton;
    private JTextField searchField;
    private JButton searchButton;

    public UserManagementPanel() {
        this.userController = new UserController();

        initComponents();
        setupLayout();
        setupEventListeners();
        refreshData();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252));

        // 表格列名
        String[] columnNames = { "用户ID", "学号", "姓名", "手机", "邮箱", "用户类型", "注册时间" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        userTable = new JTable(tableModel);
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userTable.setRowHeight(30);

        // 添加排序功能
        tableSorter = new TableRowSorter<>(tableModel);
        userTable.setRowSorter(tableSorter);

        // 配置表头样式
        JTableHeader header = userTable.getTableHeader();
        header.setFont(new Font("Microsoft YaHei", Font.BOLD, 12));
        header.setBackground(new Color(243, 244, 246));
        header.setForeground(new Color(75, 85, 99));
        header.setReorderingAllowed(false);

        // 美化表格
        styleTable(userTable);

        // 简化排序配置，让系统自动处理
        // setupColumnComparators();

        // 设置列宽
        userTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        userTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        userTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        userTable.getColumnModel().getColumn(3).setPreferredWidth(120);
        userTable.getColumnModel().getColumn(4).setPreferredWidth(150);
        userTable.getColumnModel().getColumn(5).setPreferredWidth(80);
        userTable.getColumnModel().getColumn(6).setPreferredWidth(120);

        // 按钮
        resetPasswordButton = new JButton("重置密码");
        deleteUserButton = new JButton("删除用户");
        refreshButton = new JButton("刷新");
        searchButton = new JButton("搜索");

        searchField = new JTextField(15);

        // 美化组件
        styleTextField(searchField);
        styleButton(resetPasswordButton, new Color(245, 158, 11), Color.WHITE);
        styleButton(deleteUserButton, new Color(239, 68, 68), Color.WHITE);
        styleButton(refreshButton, new Color(59, 130, 246), Color.WHITE);
        styleButton(searchButton, new Color(59, 130, 246), Color.WHITE);

        resetPasswordButton.setEnabled(false);
        deleteUserButton.setEnabled(false);
    }

    private void setupLayout() {
        // 现代化顶部工具栏
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolPanel.setBackground(new Color(255, 255, 255));
        toolPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel searchLabel = createStyledLabel("搜索:");
        toolPanel.add(searchLabel);
        toolPanel.add(searchField);
        toolPanel.add(searchButton);
        toolPanel.add(Box.createHorizontalStrut(25));

        toolPanel.add(refreshButton);
        toolPanel.add(Box.createHorizontalStrut(10));
        toolPanel.add(resetPasswordButton);
        toolPanel.add(deleteUserButton);

        // 现代化表格面板
        JScrollPane scrollPane = new JScrollPane(userTable);
        scrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)));
        scrollPane.getViewport().setBackground(new Color(255, 255, 255));

        // 现代化底部统计面板
        JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statsPanel.setBackground(new Color(255, 255, 255));
        statsPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel totalUsersLabel = createStyledLabel("总用户数: 0");
        JLabel studentsLabel = createStyledLabel("学生用户: 0");
        JLabel adminsLabel = createStyledLabel("管理员: 0");
        JLabel todayRegistrationsLabel = createStyledLabel("今日注册: 0");

        statsPanel.add(totalUsersLabel);
        statsPanel.add(Box.createHorizontalStrut(25));
        statsPanel.add(studentsLabel);
        statsPanel.add(Box.createHorizontalStrut(25));
        statsPanel.add(adminsLabel);
        statsPanel.add(Box.createHorizontalStrut(25));
        statsPanel.add(todayRegistrationsLabel);

        add(toolPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(statsPanel, BorderLayout.SOUTH);
    }

    private void setupEventListeners() {
        refreshButton.addActionListener(_ -> refreshData());

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSearch();
            }
        });

        searchField.addActionListener(_ -> handleSearch());

        resetPasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                resetSelectedUserPassword();
            }
        });

        deleteUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedUser();
            }
        });

        // 表格选择事件
        userTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                boolean hasSelection = userTable.getSelectedRow() >= 0;
                resetPasswordButton.setEnabled(hasSelection);
                deleteUserButton.setEnabled(hasSelection);
            }
        });
    }

    public void refreshData() {
        try {
            List<User> users = userController.getAllUsers();

            // 清空表格
            tableModel.setRowCount(0);

            // 填充数据
            for (User user : users) {
                Object[] row = {
                        user.getUserId(),
                        user.getStudentId(),
                        user.getName(),
                        user.getPhone(),
                        user.getEmail(),
                        user.isAdmin() ? "管理员" : "学生",
                        user.getCreateTime() != null ? user.getCreateTime().toString().substring(0, 16) : "N/A"
                };
                tableModel.addRow(row);
            }

            // 更新统计信息
            updateStatistics(users);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载用户信息失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateStatistics(List<User> users) {
        int total = users.size();
        int students = 0;
        int admins = 0;

        for (User user : users) {
            if (user.isAdmin()) {
                admins++;
            } else {
                students++;
            }
        }

        // 更新统计标签
        Component[] components = ((JPanel) getComponent(2)).getComponents();
        if (components.length >= 7) {
            ((JLabel) components[0]).setText("总用户数: " + total);
            ((JLabel) components[2]).setText("学生用户: " + students);
            ((JLabel) components[4]).setText("管理员: " + admins);
            ((JLabel) components[6]).setText("今日注册: 0"); // 这里可以添加今日注册统计
        }
    }

    private void handleSearch() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            refreshData();
            return;
        }

        try {
            List<User> users = userController.searchUsers(keyword);

            // 清空表格
            tableModel.setRowCount(0);

            // 填充搜索结果
            for (User user : users) {
                Object[] row = {
                        user.getUserId(),
                        user.getStudentId(),
                        user.getName(),
                        user.getPhone(),
                        user.getEmail(),
                        user.isAdmin() ? "管理员" : "学生",
                        user.getCreateTime() != null ? user.getCreateTime().toString().substring(0, 16) : "N/A"
                };
                tableModel.addRow(row);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "搜索失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void resetSelectedUserPassword() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow < 0)
            return;

        String studentId = (String) tableModel.getValueAt(selectedRow, 1);
        String name = (String) tableModel.getValueAt(selectedRow, 2);

        int option = JOptionPane.showConfirmDialog(this,
                "确定要重置用户 " + name + "(" + studentId + ") 的密码吗？\n重置后密码将变为：123456",
                "确认重置", JOptionPane.YES_NO_OPTION);

        if (option == JOptionPane.YES_OPTION) {
            try {
                int userId = (Integer) tableModel.getValueAt(selectedRow, 0);
                boolean success = userController.resetPassword(userId, "123456");

                if (success) {
                    JOptionPane.showMessageDialog(this, "密码重置成功！新密码为：123456",
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "密码重置失败!", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "密码重置失败: " + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void deleteSelectedUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow < 0)
            return;

        String studentId = (String) tableModel.getValueAt(selectedRow, 1);
        String name = (String) tableModel.getValueAt(selectedRow, 2);
        String userType = (String) tableModel.getValueAt(selectedRow, 5);

        if ("管理员".equals(userType)) {
            JOptionPane.showMessageDialog(this, "不能删除管理员用户!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int option = JOptionPane.showConfirmDialog(this,
                "确定要删除用户 " + name + "(" + studentId + ") 吗？\n此操作不可恢复！",
                "确认删除", JOptionPane.YES_NO_OPTION);

        if (option == JOptionPane.YES_OPTION) {
            try {
                int userId = (Integer) tableModel.getValueAt(selectedRow, 0);
                boolean success = userController.deleteUser(userId);

                if (success) {
                    JOptionPane.showMessageDialog(this, "用户删除成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshData();
                } else {
                    JOptionPane.showMessageDialog(this, "删除失败!", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 创建样式化标签
     */
    private JLabel createStyledLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        label.setForeground(new Color(75, 85, 99));
        return label;
    }

    /**
     * 美化表格样式
     */
    private void styleTable(JTable table) {
        table.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        table.setBackground(new Color(255, 255, 255));
        table.setForeground(new Color(55, 65, 81));
        table.setGridColor(new Color(229, 231, 235));
        table.setSelectionBackground(new Color(219, 234, 254));
        table.setSelectionForeground(new Color(30, 64, 175));

        // 表头样式
        table.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        table.getTableHeader().setBackground(new Color(249, 250, 251));
        table.getTableHeader().setForeground(new Color(55, 65, 81));
        table.getTableHeader().setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 231, 235)));
    }

    /**
     * 美化按钮样式
     */
    private void styleButton(JButton button, Color backgroundColor, Color textColor) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBackground(backgroundColor);
        button.setForeground(textColor);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(backgroundColor.darker(), 1),
                BorderFactory.createEmptyBorder(8, 16, 8, 16)));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    /**
     * 美化输入框样式
     */
    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(200, 30));
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(5, 8, 5, 8)));
        textField.setBackground(new Color(255, 255, 255));

        // 聚焦时的边框效果
        textField.addFocusListener(new java.awt.event.FocusListener() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(64, 158, 255), 2),
                        BorderFactory.createEmptyBorder(4, 7, 4, 7)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                        BorderFactory.createEmptyBorder(5, 8, 5, 8)));
            }
        });
    }

    /**
     * 设置表格列的排序比较器
     */
    private void setupColumnComparators() {
        // 用户ID列 - 数字排序
        tableSorter.setComparator(0, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                try {
                    return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
                } catch (NumberFormatException e) {
                    return o1.compareTo(o2);
                }
            }
        });

        // 学号列 - 字符串排序
        tableSorter.setComparator(1, String.CASE_INSENSITIVE_ORDER);

        // 姓名列 - 字符串排序
        tableSorter.setComparator(2, String.CASE_INSENSITIVE_ORDER);

        // 手机列 - 字符串排序
        tableSorter.setComparator(3, String.CASE_INSENSITIVE_ORDER);

        // 邮箱列 - 字符串排序
        tableSorter.setComparator(4, String.CASE_INSENSITIVE_ORDER);

        // 用户类型列 - 类型优先级排序
        tableSorter.setComparator(5, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return getUserTypePriority(o1) - getUserTypePriority(o2);
            }

            private int getUserTypePriority(String userType) {
                switch (userType) {
                    case "管理员":
                        return 1;
                    case "学生":
                        return 2;
                    default:
                        return 999;
                }
            }
        });

        // 注册时间列 - 时间戳排序
        tableSorter.setComparator(6, String.CASE_INSENSITIVE_ORDER);
    }
}
